package com.baijiayun.live.ui.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatImageView
import com.baijiayun.live.ui.R
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import kotlin.math.max

class RoundImageView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    AppCompatImageView(context, attrs, defStyleAttr) {
    private val ratio = 1.0f
    private var width = 0f
    private var height = 0f
    private lateinit var mPaint: Paint
    private lateinit var oval: RectF

    constructor(context: Context) : this(context, null) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
        init(context, attrs)
    }

    init {
        init(context, attrs)
    }

    fun setCircleBackgroundColor(@ColorInt color: Int) {
        mPaint.color = color
    }


    @SuppressLint("CustomViewStyleable")
    private fun init(context: Context, attrs: AttributeSet?) {
        mPaint = Paint()
        mPaint.setStyle(Paint.Style.FILL)
        mPaint.setAntiAlias(true)
        mPaint.setStrokeWidth(4f)
        mPaint.setColor(
            ThemeDataUtil.getColorFromThemeConfigByAttrId(
                getContext(),
                R.attr.base_theme_live_product_color
            )
        )
        oval = RectF()
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        width = measuredWidth.toFloat()
        height = measuredWidth.toFloat()
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        val x = getWidth().toFloat()
        val y = getHeight().toFloat()
        val radius = y / 2
        oval.set(x / 2 - radius, y / 2 - radius, x / 2 + radius, y / 2 + radius)
        //startAngle普通坐标系，-90为12点，sweepAngle if >0 -->顺时针 else <0 -->逆时针
        //startAngle普通坐标系，-90为12点，sweepAngle if >0 -->顺时针 else <0 -->逆时针
        canvas.drawArc(oval, -90f, 360.0f * ratio, false, mPaint)
        super.onDraw(canvas)
    }
}